<?php

/**
 * ajax actions.
 *
 * @package    ideas
 * @subpackage ajax
 * @author     AlvaroLara
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ajaxActions extends sfActions
{

  public function preExecute()
  {
    if(!$this->getRequest()->isXmlHttpRequest())
    {
      return sfView::NONE;
    }

    return parent::preExecute();
  }

  public function executeRankIdea(sfWebRequest $request)
  {
    $idea = IdeaPeer::retrieveByPk($request->getParameter('id'));

    if($this->getUser()->isAuthenticated() && is_null(IdeaUserRankingPeer::retrieveByPk($idea->getId(),$this->getUser()->getAppUser()->getId())))
    {
      $relation = new IdeaUserRanking();
      $relation->setIdeaId($idea->getId());
      $relation->setUserId($this->getUser()->getAppUser()->getId());
      $relation->save();
      $rank = ($request->getParameter('check') == 0)?$idea->rankUp():$idea->rankDown();
      return $this->renderText($rank);
    }
    else
    {
      $rank = $idea->getRank();
    }
    return $this->renderText($rank);
  }

  public function executeUpdateComments(sfWebRequest $request)
  {
    $idea = IdeaPeer::retrieveByPk($request->getParameter('id'));

    return $this->renderPartial('idea/comments',array('Idea' => $idea));
  }

  public function executeWatchNewComments(sfWebRequest $request)
  {
    $idea = IdeaPeer::retrieveByPk($request->getParameter('id'));

    $comment_count = $request->getParameter('count');

    if (count($idea->getComments()) > $comment_count)
    {
      return $this->renderPartial('ajax/comment_watch_notification',array('Idea' => $idea));
    }

    return sfView::NONE;
  }

  public function executeWatchNewIdeas(sfWebRequest $request)
  {
    $idea_count = $request->getParameter('idea_count');
    $current_count = IdeaPeer::doCount(new Criteria());

    if ($current_count > $idea_count)
    {
      return $this->renderPartial('ajax/idea_watch_notification',array('difference' => ($current_count - $idea_count)));
    }

    return sfView::NONE;
  }

  public function executeSaveComment(sfWebRequest $request)
  {
    if(!$this->getUser()->isAuthenticated())
    {
      return $this->renderText('You have to be a member to comment!');
    }

    $comment = $request->getParameter('comment');

    $this->Idea = IdeaPeer::retrieveByPk($comment['idea_id']);
    
    $comment = new Comment();

    $comment->setIdea($this->Idea);

    $form = new CommentForm($comment);

    $form->bind($request->getParameter('comment'), $request->getFiles('comment'));

    if ($form->isValid())
    {
      $form->save();
      return $this->renderPartial('idea/comments', array('Idea' => $this->Idea));
    }
  }

  public function executeGetOperations(sfWebRequest $request)
  {
    return $this->renderPartial('ajax/idea_list_actions');
  }
}
